<template>
	<view>

		<u-popup :show="show" zIndex='10073' :safeAreaInsetTop='true' mode="center" :round="20" @close="close">
			<view class="specification">
				<view class="specification_title">请选择分类</view>
				<view class="specification_title_1">
					<scroll-view scroll-y="true" style="height: 100%;">
						<view v-for="(itemall,indexall) in specification_list" :key="itemall">
							<height :hg='30'></height>
							<text class="specification_title_1_title">{{itemall.name}}</text>
							<!-- 多规格 -->
							<view class="" v-if="type==2">
								<view class="specification_title_1_content">
									<view
										:class="{'specification_title_1_content_flex':true,'specification_title_1_content_flex_activate':style[indexall].id==item.id}"
										v-for="(item,index) in itemall.item" :key="item"
										@tap="selective_specification(indexall,item.id,item.name)">
										{{item.name}}
									</view>
								</view>
							</view>
							<view class="flexs flexw d_box" v-else>
								<view class="flexc flexs d_box_item" v-for="(item,index) in itemall.item" :key="item">
									<view class="">
										{{item.name}}
									</view>
									<view class="">
										<u-number-box min='0' v-model="item.value" :name='item.id' @change='focus'>
											<view slot="minus" class="minus">
												<u-icon name="minus" size="16"></u-icon>
											</view>
											<text slot="input" style="width: 40rpx;text-align: center;"
												class="input">{{item.value}}</text>
											<view slot="plus" class="plus">
												<u-icon name="plus" color="#fff" size="16"></u-icon>
											</view>
										</u-number-box>
									</view>

								</view>
							</view>
						</view>
						<!-- 新增加菜部分 -->
						<view class="additional-dishes">
							<view class="additional-title">可选套餐</view>
							<scroll-view scroll-x="true" class="dish-list">
								<view class="dish-item" v-for="(dish, index) in additionalDishes" :key="index"
									:class="{ 'dish-item-active': dish.selected }" @tap="toggleDish(dish)">
									<text class="dish-name">{{ dish.name }}（￥{{ dish.price }}元）</text>
								</view>
							</scroll-view>
						</view>
					</scroll-view>
				</view>

				<!-- 已选规格显示 -->
				<view class="" v-if="type==2">
					<view class="selected">
						<text>已选规格:</text>
						<text v-for="(item,index) in style" :key="item">{{item.name +' 、'}}</text>
						<!-- 直接在后面追加已选菜品 -->
						    <text v-if="additionalDishes.some(dish => dish.selected)"></text>
						    <text v-for="(dish, index) in additionalDishes.filter(d => d.selected)" :key="index">
						          {{ dish.name }}{{ index < additionalDishes.filter(d => d.selected).length - 1 ? '、' : '' }}
						        </text>
					</view>
				</view>
				<view class="" v-else>
					<view class="selected" v-if="count>0">
						<text>已选规格:</text>
						<template v-for="(item,index) in spu_info">
							<text v-if="item.count>0">{{item.name}}x{{item.count}}</text>
						</template>
						<!-- 直接在后面追加已选菜品 -->
						<text v-if="additionalDishes.some(dish => dish.selected)"></text>
						<text v-for="(dish, index) in additionalDishes.filter(d => d.selected)" :key="index">
							  {{ dish.name }}{{ index < additionalDishes.filter(d => d.selected).length - 1 ? '、' : '' }}
							</text>
					</view>
				</view>
				<!-- 底部结算 -->
				<view class="sublist">
					<view class="sublist_left">
						<text>总计 </text>
						<text>
							<text>¥</text>
							{{totalPrice}}</text>
					</view>
					<view class="sublist_right" @tap="add_joinCar()">
						<view>
							<text>+</text>
							<text>加入购物车</text>
						</view>
						<view>add to cart</view>
					</view>
				</view>
				<view class="close_view" @tap="close(),style=[]">
					<u-icon name="close-circle" color="#333" size="80"></u-icon>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		store_itemPrice,
		store_item,
		order_joinCar,
	} from "@/api/comm.js"
	export default {
		name: "specification",
		props: ['show', 'order_id', 'store_id', 'activate_data', 'type'],
		data() {
			return {
				orderprive: '',
				fishprices: '',
				style: [], //规格动态样式
				specification_list: [],
				spu_info: [],
				count: 0,
				
				additionalDishes: [{
						name: '凉拌黄瓜',
						price: 8,
						selected: false
					},
					{
						name: '酸辣土豆丝',
						price: 12,
						selected: false
					},
					{
						name: '香辣鸡翅',
						price: 15,
						selected: false
					},
					{
						name: '水果沙拉',
						price: 10,
						selected: false
					}
				]
			};
		},
		watch: {
			 
			orderprive(newval, oldval) {
				deep: true // 开启深度监听 专门对付复杂数据类型
				immediate: true // 首次监听 一打开页面就想监听
				this.count = 0
				this.spu_info.forEach(item => {
					this.count = this.count + item.count
				})

			}
		},
		computed: {
			totalPrice() {
				let orderPrice = parseFloat(this.orderprive) || 0;
				let fishPrice = parseFloat(this.fishprices) || 0;
				return (orderPrice + fishPrice).toFixed(2);
			}
		},

		methods: {
			toggleDish(dish) {
				dish.selected = !dish.selected; // 切换选中状态
				this.calculateTotalPrice(); // 重新计算总价
			},

			// 计算总价（包括可加菜品）
			calculateTotalPrice() {
				let total = 0;
				this.additionalDishes.forEach(dish => {
					if (dish.selected) {
						total += dish.price; // 累加选中菜品的价格
					}
				});
				this.fishprices = total.toFixed(2); // 更新总价
			},
			focus(e) {
				let name;
				this.specification_list.forEach(item => {
					item.item.forEach(item1 => {
						if (item1.id == e.name) {
							name = item1.name
						}
					})
				})
				if (this.spu_info.length > 0) {
					this.spu_info.forEach(item => {
						if (item.spu_id == e.name) {
							item.count = e.value
						}
					})
				} else {
					this.spu_info.push({
						spu_id: e.name,
						count: e.value,
						name: name
					})
				}
				this.$forceUpdate()
				this.store_itemPriceApi()
			},
			async selective_specification(index, id, name) {
				this.$set(this.style[index], 'id', id)
				this.$set(this.style[index], 'name', name)
				this.store_itemPriceApi()
			},
			async specification(e) {
				this.specification_list = []
				let data = await store_item({
					goods_id: this.order_id
				})
				// console.log(JSON.stringify(data, null, 2)); // 美化输出
				if (data.code == 1) {
					this.style = []
					this.spu_info = []
					if (this.type == 2) {
						data.data.specs.forEach(res => {
							this.style.push({
								id: res.item[0].id,
								name: res.item[0].name
							})
						})
					} else {
						data.data.specs.forEach(res => {
							res.item.forEach(item1 => {
								item1.value = 0
								this.spu_info.push({
									spu_id: item1.id,
									count: 0,
									name: item1.name
								})
							})
						})
					}

					this.specification_list.push(...data.data.specs)
					this.store_itemPriceApi()
					
					//可选菜品
					this.additionalDishes = data.data.additionalDishes;
					// // 重置可选菜品的选中状态
					// this.additionalDishes.forEach(dish => {
					//     dish.selected = false;
					// })
					// this.fishPrice = 0;
				}

			},
			// 价格计算
			async store_itemPriceApi() {
				let str = ''
				let spu = []
				if (this.type == 2) {
					this.style.forEach((res, index) => {
						// if (index == (this.style.length - 1)) {
						// 	str += res.id
						// } else {
						str += res.id + '_'
						// }
					})
					str = str.substring(0, str.length - 1)
				} else {
					this.spu_info.forEach(item => {
						if (item.count > 0) {
							spu.push({
								count: item.count,
								spu_id: item.spu_id
							})
						}
					})
				}

				let data = await store_itemPrice({
					goods_id: this.order_id,
					spu_id: str,
					spu_info: spu
				})
				if (data.code == 1) {
					let num = data.data.price
					this.orderprive = num
				}

			},
			// 添加购物车
			async add_joinCar() {
				if (!uni.getStorageSync('userinfo')) {
					this.$emit('login')
					return
				}
				let str = ''
				let spu = []
				let dish_info = '' // 存储已选菜品名称
				if (this.type == 2) {
					// 多规格
					this.style.forEach((res, index) => {
						if (index == (this.style.length - 1)) {
							str += res.id
						} else {
							str += res.id + '_'
						}
					})
				} else {
					// 单规格
					this.spu_info.forEach(item => {
						if (item.count > 0) {
							spu.push({
								count: item.count,
								spu_id: item.spu_id
							})
						}
					})
				}
				// 处理已选可选菜品
				let selectedDishes = this.additionalDishes.filter(dish => dish.selected);
				if (selectedDishes.length > 0) {
					dish_info = selectedDishes.map(dish => dish.name).join('、'); // 连接菜品名称
				}
				let total_price = this.totalPrice; // 直接使用 computed 计算的值
				let data = await order_joinCar({
					store_id: this.store_id,
					goods_id: this.order_id,
					spu_id: str,
					count: 1,
					order_type: this.activate_data,
					spu_info: spu,
					dish_info: dish_info, // 传递已选菜品
					total_price:total_price
				})
				if (data.code == 1) {
					setTimeout(() => {
						this.$emit('order')
					}, 500)
					uni.showToast({
						title: data.msg,
						icon: "none"
					})
					this.spu_info = []
					this.style = []
					this.close()
				} else {
					uni.showToast({
						title: data.msg,
						icon: "none"
					})
				}
			},


			close() {
				this.spu_info = []
				this.style = []
				this.fishprices = 0
				this.$emit('close')
			}
		}
	}
</script>

<style lang="scss">
	/* 新增加菜样式 */
	.additional-dishes {
		margin-top: 40rpx;
		padding: 0 0rpx;

		.additional-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #676767;
			margin-bottom: 20rpx;
		}

		.dish-list {
			display: flex;
			flex-wrap: nowrap;
			overflow-x: auto;
			white-space: nowrap;

			.dish-item {
				display: inline-flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 20rpx 30rpx;
				margin-right: 20rpx;
				border: 1rpx solid #eee;
				border-radius: 10rpx;
				background-color: #fff;
				transition: all 0.3s ease;

				.dish-name {
					font-size: 25rpx;
					color: #333;
				}

				.dish-price {
					font-size: 24rpx;
					color: #FF0000;
					margin-top: 10rpx;
				}

				&.dish-item-active {
					background-color: #F4FCFF;
					border-color: #6F3810;
					color: #6F3810;
				}
			}
		}
	}

	.d_box {
		.d_box_item {
			font-size: 34rpx;
			color: #3d3d3d;
			width: 45%;
			margin-bottom: 20rpx;
		}
	}

	.specification {
		width: 688rpx;
		background: #FFFFFF;
		border-radius: 12rpx;
		position: relative;
		z-index: 10074;
		padding-bottom: 20rpx;
		.specification_title {
			text-align: center;
			font-size: 38rpx;
			font-weight: 600;
			color: #353535;
			margin: 0 auto;
		}
		.specification_title_1 {
			width: 95%;
			height: 600rpx;
			margin: 0 auto;
			.specification_title_1_title {
				font-size: 32rpx;
				font-weight: 600;
				color: #676767;
				display: inline-block;
				padding: 20rpx 0;
			}
			.specification_title_1_content {
				display: flex;
				overflow-x: auto;
				display: -webkit-box;
				-webkit-overflow-scrolling: touch;
				.specification_title_1_content_flex_activate {
					background: #F4FCFF !important;
					border: 1rpx solid #6F3810 !important;
					color: #6F3810 !important;
				}
				.font_sizi_1 {
					color: #6F3810;
				}
				.font_sizi_2 {
					border-left: 1rpx solid #6F3810;
				}
				.specification_title_1_content_flex {
					height: 63rpx;
					background: #FFFFFF;
					border-radius: 14rpx;
					border: 1rpx solid #F1F1F1;
					margin-right: 20rpx;
					text-align: center;
					line-height: 63rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #343434;
					padding: 0 40rpx;
				}
			}
		}

		.close_view {
			position: absolute;
			top: -15rpx;
			right: 10rpx;
		}
	}

	.selected {
		width: 688rpx;
		padding: 5rpx 0;
		background: #F5F5F5;
		margin-top: 40rpx;

		text {
			font-size: 24rpx;
			font-weight: 400;
			color: #363636;
		}

		text:nth-child(1) {
			font-size: 24rpx;
			font-weight: 400;
			color: #676767;
			padding: 0 20rpx;
			margin-left: 10rpx;
		}
	}

	.selectedfish {
		width: 688rpx;
		padding: 5rpx 0;
		background: #F5F5F5;
		margin-top: 3rpx;

		text {
			font-size: 24rpx;
			font-weight: 400;
			color: #363636;
		}

		text:nth-child(1) {
			font-size: 24rpx;
			font-weight: 400;
			color: #676767;
			padding: 0 20rpx;
			margin-left: 10rpx;
		}
	}

	.sublist {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx 40rpx 0;
		.sublist_left {
			text:nth-child(1) {
				font-size: 28rpx;
				font-weight: 600;
				color: #363636;
			}
			text:nth-child(2) {
				font-size: 28rpx;
				font-weight: 600;
				color: #FF0000;
				text:nth-child(1) {
					font-size: 28rpx;
					font-weight: 600;
					color: #FF0000;
					font-size: 24rpx;
				}
			}
		}
		.sublist_right {
			width: 234rpx;
			padding: 10rpx 0;
			background: #6F3810;
			border-radius: 12rpx;
			font-size: 32rpx;
			font-weight: 500;
			color: #F3FCFF;
			text-align: center;
		}
	}
	.minus {
		width: 25px;
		height: 25px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		@include flex;
		justify-content: center;
		align-items: center;
	}
	.input {
		padding: 0 10px;
	}
	.plus {
		width: 25px;
		height: 25px;
		border-width: 1px;
		background-color: #6F3810;
		border-color: #6F3810;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		@include flex;
		justify-content: center;
		align-items: center;
	}
</style>